// utils/request.js
const BASE_URL = 'http://localhost:8080';
// const BASE_URL = '';

function getRequestHeader() {
  const token = wx.getStorageSync('token');
  return {
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
  };
}

function handleResponse(response) {
  if (response.statusCode >= 200 && response.statusCode < 300) {
    return response.data;
  } else {
    return Promise.reject(response);
  }
}

function handleErrorResponse(error) {
  console.error('网络请求错误:', error);
  return Promise.reject(error);
}

function get(url, params = {}) {
  const requestUrl = `${BASE_URL}${url}`;
  return new Promise((resolve, reject) => {
    wx.request({
      url: requestUrl,
      method: 'GET',
      data: params,
      header: getRequestHeader(),
      success: (response) => {
        resolve(handleResponse(response));
      },
      fail: (error) => {
        reject(handleErrorResponse(error));
      }
    });
  });
}

function post(url, data = {}) {
  const requestUrl = `${BASE_URL}${url}`;
  return new Promise((resolve, reject) => {
    wx.request({
      url: requestUrl,
      method: 'POST',
      data: data,
      header: getRequestHeader(),
      success: (response) => {
        resolve(handleResponse(response));
      },
      fail: (error) => {
        reject(handleErrorResponse(error));
      }
    });
  });
}

function put(url, data = {}) {
  const requestUrl = `${BASE_URL}${url}`;
  return new Promise((resolve, reject) => {
    wx.request({
      url: requestUrl,
      method: 'PUT',
      data: data,
      header: getRequestHeader(),
      success: (response) => {
        resolve(handleResponse(response));
      },
      fail: (error) => {
        reject(handleErrorResponse(error));
      }
    });
  });
}

function del(url, params = {}) {
  const requestUrl = `${BASE_URL}${url}`;
  return new Promise((resolve, reject) => {
    wx.request({
      url: requestUrl,
      method: 'DELETE',
      data: params,
      header: getRequestHeader(),
      success: (response) => {
        resolve(handleResponse(response));
      },
      fail: (error) => {
        reject(handleErrorResponse(error));
      }
    });
  });
}

module.exports = {
  get,
  post,
  put,
  del
};